using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Configuration;
using Safira.Spome.Merge.Properties;
using System.IO;
using System.Globalization;
using Safira.Spome.Merge.SpomeWebRef;
using System.Net;
using System.Threading;
using Safira.Spome.Merge.Workers;

namespace Safira.Spome.Merge
{
    public partial class SpomeMerge : Form
    {
        #region Private MyProxy

        SpomeServices myProxy1 = null;
        SpomeServices myProxy2 = null;
        
        #endregion 

        #region Private Log

        FileStream logFile;
        StreamWriter logWriter;

        #endregion

        public SpomeMerge()
        {
            InitializeComponent();
            MyInitializeComponent();

            #region Initialize Logging

            logFile = new FileStream( "log.txt", FileMode.Append, FileAccess.Write );
            logWriter = new StreamWriter( logFile );

            #endregion

            #region Initialize Proxy1

            if ( ! string.IsNullOrEmpty(ConfigurationManager.AppSettings["WebService1Url"] ))
            {
                try
                {
                    myProxy1 = new SpomeWebRef.SpomeServices();
                    myProxy1.Url = ConfigurationManager.AppSettings[ "WebService1Url" ];
                }
                catch ( InvalidOperationException e )
                {
                    string logme = string.Format(CultureInfo.InvariantCulture,"{0}: {1}\n",System.DateTime.UtcNow.ToString(), e.Message);

                    myProxy1 = null;

                    logWriter.Write( logme );
                }
            }

            #endregion

            #region Initialize Proxy2

            if ( ! string.IsNullOrEmpty(ConfigurationManager.AppSettings["WebService2Url"] ))
            {
                try
                {
                    myProxy2 = new SpomeWebRef.SpomeServices();
                    myProxy2.Url = ConfigurationManager.AppSettings[ "WebService2Url" ];
                }
                catch ( InvalidOperationException e )
                {
                    string logme = string.Format( CultureInfo.InvariantCulture, "{0}: {1}\n", System.DateTime.UtcNow.ToString(), e.Message );

                    myProxy2 = null;

                    logWriter.Write( logme );
                }
            }

            #endregion

            
        }

        /// <summary>
        /// Initializes my components.
        /// </summary>
        private void MyInitializeComponent()
        {
            #region Control Handlers

            buttonLoad.MouseClick += new MouseEventHandler( buttonLoad_MouseClick );

            #endregion

            IsProxyConnected();
        }

        /// <summary>
        /// Handles the MouseClick event of the buttonLoad control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>        
        void buttonLoad_MouseClick( object sender, MouseEventArgs e )
        {
            #region Proxy Test
            if ( ! IsProxyConnected() )
            {
                return;
            }
            #endregion

            #region Setting Proxy Credentials

            NetworkCredential credentials = new NetworkCredential( txtUser.Text, txtPassword.Text );

            myProxy1.Credentials = credentials;
            myProxy2.Credentials = credentials;

            #endregion

            #region Create Load Worker 1

            LoadSiteWorker loadWorker1 = new LoadSiteWorker( myProxy1 );
            loadWorker1.Request = new LoadSiteRequest();
            loadWorker1.Request.Url = textUrl1.Text;
            loadWorker1.Tree = treeView1;

            #endregion

            #region Create Load Worker 2

            LoadSiteWorker loadWorker2 = new LoadSiteWorker( myProxy2 );
            loadWorker2.Request = new LoadSiteRequest();
            loadWorker2.Request.Url = textUrl2.Text;
            loadWorker2.Tree = treeView2;

            #endregion

            #region Create Threads 

            Thread myTread1 = new Thread( new ThreadStart( loadWorker1.Work ) );
            Thread myTread2 = new Thread( new ThreadStart( loadWorker2.Work ) );

            #endregion 

            #region Start Threads

            myTread1.Start();
            myTread2.Start();

            #endregion

            return;
        }

        /// <summary>
        /// Raises the <see cref="E:Resize"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnResize( EventArgs e )
        {
            base.OnResize( e );

            IsProxyConnected();
        }

        /// <summary>
        /// Determines whether [is proxy connected].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if [is proxy connected]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsProxyConnected()
        {
          return ( ( myProxy1 != null ) && ( myProxy2 != null ) );
        }

       
    }
}